import { withPageContainer } from '@/components';
import { useCallback, useRef, useState } from 'react';
import { Input } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import { useRequest } from 'ahooks';
import { Decimal } from 'decimal.js';
import dayjs from 'dayjs';
import { useUserStore } from '@/common/hox/userStore';
import { CouponSelectPopRefType, Modal, CouponSelect } from '@/components';
import { OrderConfirmMovieTitle, TicketModeSelect } from '../components';
import { SeatAuto } from '@/pages/movie/seatSelect/components';
// import subscribeMessage from '@/utils/subscribeMessage';
import { pay, openPay } from '@/utils';
import { useMovieStore } from '@/common/hox/movieStore';
import { PageUrlEnum, CouponBatchStatusEnum } from '@/utils/enum';
import { usePageShow } from '@/common/hook/usePage';
import { getUserContactMobile, movieCreateOrder } from '@/service';
import { TicketModeEnum, TicketModeMap } from '@/utils/enum';
import { phoneReg } from '@/common/utils';
import { useTicketModeStore } from '@/common/hox/ticketModeStore';
import { PageUrlMap } from '@/utils/enum';
import { CustomNavBar } from '@/components';
import { Close } from '@nutui/icons-react-taro';
import styles from './index.module.less';
// router params
type RouterParamType = {
    movieId: string;
};
const ConfirmPage = () => {
    const cinemaUrl = PageUrlMap.get(PageUrlEnum.CinemaList);
    const { params } = useRouter<RouterParamType>();
    const { movieId } = params;
    const [contactMobile, setContactMobile] = useState<string>('');
    const { userInfo } = useUserStore();

    useRequest(getUserContactMobile, {
        ready: Boolean(userInfo?.isBindPhone),
        onSuccess: (res) => {
            if (phoneReg.phone.test(res)) {
                setContactMobile(res);
            } else setContactMobile('');
        },
    });

    const {
        refreshCouponInfo,
        cinema: { cinemaInfo },
        movie: { movieDetail },
        schedule: { acceptChangeSeat, scheduleDetail, issueTicketMode },
        coupon: { selectCoupon, setSelectCoupon },
        seat: { seatTotalPrice, seatList },
        combination: { combinationInfo },
        paymentAmount,
    } = useMovieStore((store) => [
        store.cinema.cinemaInfo,
        store.movie.movieDetail,
        store.schedule.scheduleDetail,
        store.schedule.scheduleSeatInfo,
        store.schedule.issueTicketMode,
        store.schedule.acceptChangeSeat,
        store.coupon.selectCoupon,
        store.coupon.setSelectCoupon,
        store.combination.combinationInfo,
        store.seat.seatTotalPrice,
        store.seat.seatList,
        store.paymentAmount,
        store.refreshCouponInfo,
    ]);
    const { ticketModeList } = useTicketModeStore();
    const showTimeMinute = scheduleDetail
        ? dayjs(scheduleDetail.showTime).diff(new Date(), 'minute')
        : 0;
    const specialModeDisabled = Boolean(scheduleDetail && showTimeMinute < 45);

    usePageShow(() => {
        if (!movieDetail || !scheduleDetail || !cinemaInfo) {
            cinemaUrl && Taro.redirectTo({ url: `${cinemaUrl}?movieId=${movieId}` });
        } else {
            setSelectCoupon(undefined);
        }

        if (userInfo?.mobile) {
            setContactMobile(userInfo?.mobile);
        }

        if (showTimeMinute <= 30) {
            Taro.showToast({
                title: '影片离开场时间小于30分钟了，请确认是否有足够的观影时间～',
                icon: 'none',
                duration: 2000,
            });
        }
        if (issueTicketMode === TicketModeEnum.SlowTicket && specialModeDisabled) {
            Taro.showToast({
                title: '影片开场时间小于45分钟，建议选择快速购票，避免失败～',
                icon: 'none',
                duration: 2000,
            });
        }
    });

    const [agreement, setAgreement] = useState(false);
    const [reAgreement, setReAgreement] = useState(false);
    const [submitModalVisible, setSubmitModalVisible] = useState(false);

    const [availableCoupon, setAvailableCoupon] = useState<Coupon.ListItem[]>([]);
    const couponSelectRef = useRef<CouponSelectPopRefType>(null);
    // 待支付下单确认二次弹窗
    const handleSubmit = async () => {
        // if (!movieBrandInfo) return
        if (
            availableCoupon?.length > 0 &&
            !selectCoupon &&
            issueTicketMode === TicketModeEnum.SlowTicket
        ) {
            const { confirm } = await Taro.showModal({
                title: '提示',
                content: `您有${availableCoupon.length}张优惠券，确定不使用吗？`,
                cancelText: '继续下单',
                confirmText: '使用优惠',
            });
            if (confirm) return couponSelectRef.current?.open();
        }
        // 手机号校验
        if (!phoneReg.phone.test(contactMobile)) {
            return Taro.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        }
        // 同意购票协议
        if (!agreement) {
            Taro.pageScrollTo({
                scrollTop: 9999,
                // selector: '.' + styles.agreement,
                duration: 300,
                complete: function (res) {
                    console.log(res);
                },
            });
            return Taro.showToast({ title: '请同意购票须知～', icon: 'none', duration: 2000 });
        }
        // 开场前45分钟 特惠购票不可用
        if (issueTicketMode === TicketModeEnum.SlowTicket && specialModeDisabled)
            return Taro.showToast({ title: '当前场次已停售,您可选择其它场次', icon: 'none' });
        setSubmitModalVisible(true);
    };

    // 创建订单
    const movieCreateOrderApi = useRequest(
        () => {
            try {
                if (
                    !movieDetail ||
                    !scheduleDetail ||
                    issueTicketMode === undefined ||
                    !cinemaInfo
                ) {
                    Taro.showToast({ title: '订单数据不完整，请重试', icon: 'none' });
                    return Promise.reject('Missing required data');
                }

                if (!seatList || seatList.length === 0) {
                    Taro.showToast({ title: '请选择座位', icon: 'none' });
                    return Promise.reject('No seats selected');
                }

                const openUrlParam = Taro.getStorageSync('open_url_param') || {};
                const orderData = {
                    channel: openUrlParam.channel || '',
                    comeFrom: openUrlParam.sid || '',
                    moveCode: movieDetail.movieCode,
                    cinemaCode: cinemaInfo.cinemaId || cinemaInfo.cinemaCode,
                    isvId: scheduleDetail.isvId,
                    mobile: contactMobile,
                    fastTicket: issueTicketMode === TicketModeEnum.FastTicket,
                    switchSeat: Boolean(acceptChangeSeat),
                    showId: scheduleDetail.showId,
                    seatItems: seatList.map(({ columnNo, rowNo, seatNo }) => ({
                        columnNo: String(columnNo),
                        rowNo: String(rowNo),
                        seatName: String(seatNo),
                    })),
                    couponCode: combinationInfo?.couponCode || selectCoupon?.couponCode || '',
                };

                const isOpenPurchase = userInfo?.purchaseType !== 1;
                console.log(isOpenPurchase);
                return movieCreateOrder(orderData, isOpenPurchase ? 'open' : '');
            } catch (error) {
                console.error('Create order error:', error);
                Taro.showToast({ title: '创建订单失败，请重试', icon: 'none' });
                return Promise.reject(error);
            }
        },
        {
            manual: true,
            onBefore: () => Taro.showLoading({
                title:'加载中'
            }),
            onFinally: () => Taro.hideLoading(),
            onSuccess: (res) => {
                if (!res) {
                    Taro.showToast({ title: '订单创建异常，请重试', icon: 'none' });
                    return;
                }
                refreshCouponInfo();
                userInfo?.purchaseType === 1 ? pay?.(res) : openPay(res);
            },
            onError: (error) => {
                console.error('Order API error:', error);
                Taro.showToast({ title: '订单创建失败，请重试', icon: 'none' });
            },
        }
    );

    //
    const reAgreementModalConfirm = useCallback(() => {
        if (movieCreateOrderApi.loading) return;
        setSubmitModalVisible(false);
        // 订阅消息通知
        movieCreateOrderApi.run();
    }, [movieCreateOrderApi.loading]);

    return (
        <div className={styles.page}>
            <CustomNavBar title={'确认订单'} />
            <div className={styles.content}>
                <OrderConfirmMovieTitle className={styles.card} />

                <div className={classNames(styles.seatAutoBox, styles.card)}>
                    <SeatAuto className={styles.seatAuto} ghost />
                    <div className={styles.contactMobile}>
                        <div className={styles.icon}></div>
                        <Input
                            placeholder="请输入手机号"
                            className={styles.input}
                            type="number"
                            maxlength={11}
                            value={contactMobile}
                            onInput={(e) =>
                                setContactMobile(e.detail.value.trim().replace(/\s/g, ''))
                            }
                        />
                    </div>
                    <div className={styles.tip}>手机号码将作用于出票异常联系和取票码发放</div>
                </div>

                <CouponSelect
                    ref={couponSelectRef}
                    className={styles.card}
                    onCouponListGroupChange={(groupData) =>
                        setAvailableCoupon(
                            groupData.find(([key]) => key === CouponBatchStatusEnum.enable)?.[1] ||
                                []
                        )
                    }
                />
                <TicketModeSelect className={styles.card} />

                {!agreement && (
                    <Modal visible={!agreement} className={styles.submitModal}>
                        <div className={classNames(styles.agreement, styles.agreementCard)}>
                            <div className={styles.titleBox}>
                                <div className={styles.title}>购票退改签规定协议</div>
                                <div
                                    className={styles.closeBox}
                                    onClick={() => {
                                        Taro.navigateBack();
                                    }}
                                >
                                    <Close
                                        color="var(--color-primary)"
                                        style={{ marginRight: '10px' }}
                                    />
                                </div>
                            </div>
                            <div className={styles.line}></div>
                            <div className={styles.agreementText}>
                                {[
                                    <>
                                        请确认影院、影片、场次无误，购买成功后将
                                        <div className={styles.agreementRed}>
                                            【不可退款、改签】
                                        </div>
                                        ，如因个人原因无法观影且造成损失需买家自承担，平台概不负责。
                                    </>,
                                    <>
                                        支付完成后，
                                        {ticketModeList.includes(TicketModeEnum.SlowTicket) && (
                                            <>
                                                <div className={styles.agreementRed}>
                                                    {ticketModeList.length > 1
                                                        ? TicketModeMap.get(
                                                              TicketModeEnum.SlowTicket
                                                          )
                                                        : null}
                                                    预计【15~50分钟】
                                                </div>
                                                出票，
                                            </>
                                        )}
                                        {ticketModeList.includes(TicketModeEnum.FastTicket) && (
                                            <>
                                                <div className={styles.agreementRed}>
                                                    {ticketModeList.length > 1
                                                        ? TicketModeMap.get(
                                                              TicketModeEnum.FastTicket
                                                          )
                                                        : null}
                                                    预计【15分钟内】
                                                </div>
                                                出票，
                                            </>
                                        )}
                                        个别订单可能时间略长，若无法等待，请勿下单购买。
                                    </>,
                                    <>
                                        由于影院系统不稳定等因素，存在出票失败的情况，若不能出票或所选座位已售且不接受座位调整，订单将会在
                                        <div className={styles.agreementRed}>
                                            【24小时】内自动退款。
                                        </div>
                                    </>,
                                    <>
                                        出票成功后，在所选影院的
                                        <div className={styles.agreementRed}>
                                            自助取票机或前台取票
                                        </div>
                                        。若无法取票，您可联系客服协助处理。
                                    </>,
                                    <>取票信息可在订单详情页内查看。</>,
                                ].map((dom, index) => (
                                    <div key={index} className={styles.agreementRow}>
                                        <div>{index + 1}.</div>
                                        <div className={styles.agreementRowText}>{dom}</div>
                                    </div>
                                ))}
                            </div>
                            <div
                                className={styles.btnConfirm}
                                onClick={() => {
                                    // 同意退票规则
                                    setAgreement(!agreement);
                                }}
                            >
                                {/* <Image className={styles.checkImg} src={!agreement?'https://fulu-media.oss-cn-hangzhou.aliyuncs.com/public/icon/ci--radio-unchecked.png':'https://fulu-media.oss-cn-hangzhou.aliyuncs.com/public/icon/ix--success-black.png'}/> */}
                                我已阅读并同意以上协议，确认购票
                            </div>
                        </div>
                    </Modal>
                )}
            </div>
            <div className={styles.footer}>
                <div className={styles.btnBox} onClick={handleSubmit}>
                    <div className={styles.text}>
                        <div className={styles.price}>
                            <span className={styles.small}>￥</span>
                            {paymentAmount}
                        </div>
                        <div className={styles.saving}>
                            {combinationInfo
                                ? '权益卡支付'
                                : selectCoupon
                                ? `券已抵${
                                      selectCoupon.couponType === 1
                                          ? seatTotalPrice.seatItemPrice
                                          : selectCoupon.batchValue
                                  }元`
                                : `共为您节省：￥${Decimal.sub(
                                      seatTotalPrice.totalOfficialPrice,
                                      paymentAmount
                                  ).toFixed(2)}`}
                        </div>
                    </div>
                    <div className={styles.btn}>确认购票</div>
                </div>
            </div>

            <Modal visible={submitModalVisible} className={styles.submitModal}>
                <div className={styles.modalContent}>
                    <div className={styles.modalWarn} onClick={() => setSubmitModalVisible(false)}>
                        不支持退款和改签哦~{' '}
                        <Close
                            color="var(--color-primary-text)"
                            size="16px"
                            style={{ marginLeft: '20px' }}
                        />
                    </div>
                    <div className={styles.time}>
                        当前购票模式优惠力度较大，需开场前45分钟下单，出票时间约在
                        <div className={styles.colorMain}>
                            {issueTicketMode === 0 ? '15' : '15~50'}分钟
                        </div>
                        左右。
                    </div>
                    <div className={styles.modalPrice}>
                        {!selectCoupon &&
                            issueTicketMode !== undefined &&
                            ticketModeList.length > 1 && (
                                <div className={styles.modalTicketMode}>
                                    您选择购票模式为：
                                    <div className={styles.colorMain}>
                                        {TicketModeMap.get(issueTicketMode)}
                                    </div>
                                </div>
                            )}
                        <div>
                            实付金额：<div className={styles.colorMain}>￥{paymentAmount}</div>
                        </div>
                    </div>
                </div>
                <div className={styles.submitModalFooter}>
                    {/* <div className={styles.cancel} onClick={() => setSubmitModalVisible(false)}>我再想想</div> */}
                    <div
                        className={styles.confirm}
                        onClick={() => {
                            // 同意退票规则
                            setReAgreement(!reAgreement);
                            reAgreementModalConfirm();
                        }}
                    >
                        我同意退改票协议，确认购票
                    </div>
                </div>
            </Modal>
        </div>
    );
};

export default withPageContainer(() => <ConfirmPage />);
